package DAO;

import java.io.File;
import java.io.IOException;
import java.sql.*;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.*;
import java.util.logging.FileHandler;
import java.util.logging.Formatter;
import java.util.logging.Level;
import java.util.logging.Logger;
import java.util.logging.SimpleFormatter;

import model.Message;
import server.main.server_main;

public class MessageDAO {
	private Connection cnn;
	private static final Logger logger = Logger.getLogger(MessageDAO.class.getName()); // 日志库
	public MessageDAO(Connection c)
	{
		cnn = c;
        // 设置日志级别
        logger.setLevel(Level.INFO);
        // 创建一个文件处理器
        try {
        	String path = "." + File.separator + "log" + File.separator + "messageDao.log"; //   ./log/xxx.log
            FileHandler fileHandler = new FileHandler(path);
            fileHandler.setLevel(Level.INFO);

            // 创建一个日志格式化器
            Formatter formatter = new SimpleFormatter();
            fileHandler.setFormatter(formatter);

            // 将处理器添加到日志记录器
            logger.addHandler(fileHandler);
        } catch (IOException e) {
            e.printStackTrace();
        }
	}
	
	//插入一行数据
	public boolean Insert(int user_id,int room_id,String mes)
	{
		int rs = 0;
		String sql = "INSERT INTO message(user_id,room_id,message,time) VALUES(?,?,?,?)";
		try
		{
			 LocalDateTime currentTime = LocalDateTime.now();
			 DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
			 String dateString = currentTime.format(formatter);
			 
			 System.out.println(dateString);
			 PreparedStatement stmt = cnn.prepareStatement(sql);
			 stmt.setInt(1, user_id);
			 stmt.setInt(2, room_id);
		     stmt.setString(3, mes);
		     stmt.setString(4, dateString);
		     rs = stmt.executeUpdate();
		}catch(SQLException e)
		{
			e.getMessage();
		}
		if(rs > 0)      //rs表示插入操作影响的行数
		{
			System.out.println("插入成功！");
			logger.info("插入成功");
			return true;
		}else
		{
			System.out.println("插入失败！");
			logger.info("插入失败");
			return false;
		}
	}
	
	//查询数据
	public Vector<model.Message> Query(int room_id)
	{
		logger.info("查询历史信息");
		Vector<model.Message> v = new Vector<>();
		ResultSet rs = null;
		String sql = "SELECT * FROM message where room_id = ?";
		try
		{
			PreparedStatement stmt = cnn.prepareStatement(sql);
			stmt.setInt(1, room_id);
			rs = stmt.executeQuery();
		}catch(SQLException e)
		{
			e.printStackTrace();
		}
		try {
			while(rs.next())
			{
				model.Message mes = new model.Message();
				mes.setRoomID(rs.getInt("room_id"));
				mes.setText(rs.getString("message"));
				mes.setUserID(rs.getInt("user_id"));
				mes.setTime(rs.getString("time"));
				v.add(mes);
			}
		} catch (SQLException e) {
			e.printStackTrace();
		}
		return v;
	}
	
	//向数据库中写入添加好友请求
	public String createFriendReq(int req, String reqName,int rec) {
    	System.out.println("申请人："+req+" "+reqName+"被申请人："+rec);
    	logger.info("申请人："+req+" "+reqName+"被申请人："+rec);
        String result = "error";
        String sql = "select * from user where account=?";
        try (PreparedStatement stmt = cnn.prepareStatement(sql)) {
            stmt.setInt(1, rec);
            ResultSet rs = stmt.executeQuery();
            if (rs.next()) {
            	String selectSql = "SELECT * FROM add_message WHERE req_account=? AND req_name=? AND recv_account=?";
                String insertSql = "INSERT INTO add_message (req_account,req_name, recv_account) VALUES (?,?, ?)";
                try (PreparedStatement selectStmt = cnn.prepareStatement(selectSql);
                     PreparedStatement insertStmt = cnn.prepareStatement(insertSql)) {
                    selectStmt.setInt(1, req);
                    selectStmt.setString(2, reqName);
                    selectStmt.setInt(3, rec);
                    ResultSet rs1 = selectStmt.executeQuery();
                    if (rs1.next()) {
                        // 已存在相同的条目，不需要再次插入
                        result = "ok";
                    } else {
                        // 不存在相同的条目，执行插入操作
                        insertStmt.setInt(1, req);
                        insertStmt.setString(2, reqName);
                        insertStmt.setInt(3, rec);
                        int rows = insertStmt.executeUpdate();
                        if (rows > 0) {//成功插入
                            result = "ok";
                        } else {//未能成功插入则返回-1
                            result = "failed";
                        }
                    }
                } catch (SQLException e) {
                    e.printStackTrace();
                }
            } else {
                result = "failed";
            }
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return result;
    }
	
	//从数据库中删除已被处理的好友请求
	public String deleteFriendReq(int req, String reqName, int rec) {
        String sql = "DELETE FROM add_message WHERE req_account=? AND req_name=? AND recv_account=?";
        try {
        	PreparedStatement stmt = cnn.prepareStatement(sql);
            stmt.setInt(1, req);
            stmt.setString(2, reqName);
            stmt.setInt(3, rec);
            int rows = stmt.executeUpdate();
            if (rows > 0) {
                return "ok";
            } else {
                return "failed";
            }
        } catch (SQLException ex) {
            return "failed";
        }
    }
	
	//添加好友
	public String addFriend(int mqq,int fqq,String fname,String mname) {
    	String sql1 = "INSERT INTO friends (maccount,faccount,fname) VALUES (?,?, ?)";
    	String sql2 = "INSERT INTO friends (maccount,faccount,fname) VALUES (?,?, ?)";
    	try (PreparedStatement insertStmt1 = cnn.prepareStatement(sql1);
    		 PreparedStatement insertStmt2 = cnn.prepareStatement(sql2)	) {
            insertStmt1.setInt(1, mqq);
            insertStmt1.setInt(2, fqq);
            insertStmt1.setString(3, fname);
            
            insertStmt2.setInt(1, fqq);
            insertStmt2.setInt(2, mqq);
            insertStmt2.setString(3, mname);
            int rows1 = insertStmt1.executeUpdate();
            int rows2 = insertStmt2.executeUpdate();
            if (rows1 > 0  &&  rows2 > 0) {//成功插入
                return "ok";
            } else {//未能成功插入则返回-1
            	return"failed";
            }
        } catch (SQLException e) {
            e.printStackTrace();
            return "failed";
        }
    }
	
	//从数据库中查询好友请求
	public Hashtable<Integer, String> getAddMessages(int recv_account){
		String sql = "SELECT * FROM add_message where recv_account = ?";
		ResultSet rs = null;
		Hashtable<Integer, String> messages = new Hashtable<Integer, String>();
		
		try
		{
			PreparedStatement stmt = cnn.prepareStatement(sql);
			stmt.setInt(1, recv_account);
			rs = stmt.executeQuery();
			
			while(rs.next()) {
				String req_name = rs.getString("req_name");
				int req_account = rs.getInt("req_account");
				messages.put(req_account, req_name);
			}
			return messages;
		}catch(SQLException e)
		{
			e.printStackTrace();
		}
		return null;
	}
	
	//删除好友
	public boolean deleFriend(int maccount,int faccount) {
		String sql = "DELETE FROM friends WHERE (maccount=? AND faccount=?) OR (maccount=? AND faccount=?)";		
		try
		{
			PreparedStatement stmt = cnn.prepareStatement(sql);
			stmt.setInt(1, maccount);
			stmt.setInt(2, faccount);
			stmt.setInt(3, faccount);
			stmt.setInt(4, maccount);
			int rows = stmt.executeUpdate();
			
			if(rows > 0) {
				return true;
			}else {
				return false;
			}
		}catch(SQLException e)
		{
			e.printStackTrace();
		}
		return false;
	}
	
	//处理修改用户名
	public boolean modifyName(int maccount,String name) {
		String sql = "UPDATE friends SET fname = ? WHERE faccount = ?";
		try
		{
			PreparedStatement stmt = cnn.prepareStatement(sql);
			stmt.setString(1, name);
			stmt.setInt(2, maccount);
			int rows = stmt.executeUpdate();
			
			if(rows > 0) {
				return true;
			}
		}catch(SQLException e)
		{
			e.printStackTrace();
		}
		return false;
	}
}